const express = require('express')
const path = require('path')
const request = require('request')
const multer = require('multer')
const fs = require("pn/fs")
const PSD = require('psd')
const TextToSVG = require('text-to-svg')

var router = express.Router()
// var storage = multer.diskStorage({
// 	destination: path.resolve('./upload/'),
// })

// 定义上传的文件格式
var upload = multer({
	dest: path.resolve('./upload/')
})

router.post('/photoshop', upload.single('photoshop'), async (req, res, next) => {
	let imgArr = req.body.imgArr;
	let fonts = req.body.fonts;
	try {
		imgArr = JSON.parse(imgArr)
		fonts = JSON.parse(fonts)
	} catch (error) {
		imgArr = []
		fonts = []
	}
	let filePath = req.file.path;
	let psd = PSD.fromFile(filePath);
	psd.parse();
	let doc = psd.tree().export();
	let jsonArr = []
	// return res.send(doc)
	// let json = fs.createWriteStream('json.json')
	// console.log(JSON.stringify(doc))
	for (let j = 0; j < doc.children.length; j++) {
		let jsonContent = [];
		let child = doc.children[j];
		if (child.type == 'group') {
			for (let i = 0; i < child.children.length; i++) {
				let element = child.children[i];
				let attr = {}; // 元素的属性
				//共有属性
				attr.eleid = new Date().getTime();
				attr.transform = `translate(${element.left},${element.top})`
				attr.className = 'hoveMove';
				attr.opacity = element.opacity;
				attr.rotate = 0;
				attr.rotation = '';
				attr.reverce = '';
				attr.group = ''
				attr["group-transform"] = ''
				attr._html = '';
				// 私有属性
				if (element.text) { // 文字的处理方式
					attr.type = 'text';
					let family = getFamily(element.text.font.name, fonts);
					let textBody = {
						family, // '思源黑体 CN Regular',//item.text.font.name,
						fontId: 0,
						width: element.width,
						arrList: [...element.text.value.split('\r')],
						size: element.text.font.sizes && element.text.font.sizes[0] || 30,
						align: 'left',
						fill: `rgba(${element.text.font.colors[0].join(',').slice(0, -1)})`,
						spacing: 0,
						line: 1.2,
						itailic: 0,
						bold: 0,
						underline: 0,
						scale: 1
					}
					let result;
					try {
						result = await getPath(textBody);
					} catch (error) {
						result = ''
					}
					if (result) {
						textBody.scale = textBody.size / result.height;
						attr.key = textBody;
						attr._html += " <rect id='' width='100%' height='100%' opacity='0'></rect>";
						attr._html += `<g fill="${textBody.fill}" stroke="${textBody.fill}"><g>${result.svg}</g></g>`;
						// str = str.Replace("\"", "'");
						attr.width = result.width;
						attr.height = result.height;
						attr.viewbox = `0 0 ${result.width} ${result.height}`;
						jsonContent.push(attr)
					}

				} else { // 图片的处理方式
					attr.type = 'image';
					attr.width = element.width;
					attr.height = element.height;
					attr.viewbox = `0 0 ${element.width} ${element.height}`;
					let src = getImg(element.name, imgArr);
					attr.key = {
						src: src
					}
					// console.log(attr)
					attr._html = `<g><image xlink:href='${src}!w800.src' width='${element.width}' height='${element.height}'></image></g>`;
					if (getImg(element.name, imgArr)) {
						jsonContent.push(attr)
					}
				}
			}
		}
		jsonContent.reverse();
		jsonArr.push(jsonContent)
	}
	res.send(jsonArr);
})

function getImg(name, imgArr) { // 获取对应图片
	for (let key in imgArr) {
		if (imgArr[key].name == name) return imgArr[key].src
	}
	return ''
}

function getFamily(family, fonts) {

	for (let key in fonts) {
		if (fonts[key].EnglishName == family) {
			// console.log(fonts[key].EnglishName , family, fonts[key].FontCairoName)
			return fonts[key].FontCairoName
		}
	}
	return '思源黑体 CN Regular'
}

router.post('/psd', upload.single('psd'), (req, res, next) => {
	try {
		// console.log(req.body)
		let token = req.headers.token;
		let filePath = req.file.path;
		var psd = PSD.fromFile(filePath);
		psd.parse();
		let doc = psd.tree().export();
		let obj = {};
		obj.size = doc.document;
		obj.children = [];
		// console.log(obj)
		Promise.all(Array.from(doc.children).map((item, i) => {
			return new Promise((resolve, reject) => {
				let child = {};
				if (item.type == 'layer') {
					child.eleid = new Date().getTime();
					child.transform = `translate(${item.left},${item.top})`
					child.className = 'hoveMove';
					child.opacity = item.opacity;
					child.rotate = 0;
					child.rotation = '';
					child.reverce = '';
					child.group = ''
					child["group-transform"] = ''
					child._html = '';
					if (item.text) {
						child.type = 'text';
						let textBody = {
							family: '思源黑体 CN Regular', //item.text.font.name,
							fontId: 0,
							width: item.width,
							arrList: [item.text.value],
							size: item.text.font.sizes && item.text.font.sizes[0] || 30,
							align: 'left',
							fill: `rgba(${item.text.font.colors[0].join(',').slice(0, -1)})`,
							spacing: 0,
							line: 1.2,
							itailic: 0,
							bold: 0,
							underline: 0,
							scale: 1
						}

						// console.log(textBody)
						let result = getPath(textBody);
						textBody.scale = textBody.size / result.height;
						child.key = textBody;
						child._html += " <rect id='' width='100%' height='100%' opacity='0'></rect>";
						child._html += `<g fill="${textBody.fill}" stroke="${textBody.fill}"><g>${result.svg}</g></g>`;
						// str = str.Replace("\"", "'");
						child.width = result.width;
						child.height = result.height;
						child.viewbox = `0 0 ${result.width} ${result.height}`;
						obj.children.push(child)
						// console.log(result)
						resolve(child)
					} else {
						child.type = 'image';
						child.width = item.width;
						child.height = item.height;
						child.viewbox = `0 0 ${item.width} ${item.height}`;
						let imagepath = path.resolve(`./public/psd/${new Date().getTime()}${i}.png`);
						
						psd.layers[i].image.saveAsPng(imagepath)
						.then(ok => {
							let r = request.post('http://api.aliyin.com/api/DesignerMaterial', {
								headers: {
									token: token || 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJVc2VySWQiOjMzNjM3LCJVc2VyTmFtZSI6IjE5MDUxMDE1MTkzOTU1MiIsIlVzZXJUeXBlIjoiVVUiLCJBY3Rpdml0eSI6dHJ1ZSwiRW1haWwiOm51bGwsIlBob25lIjoiMTU5NjI2NzcyMDUiLCJOaWNrTmFtZSI6IjE1OTYyNjc3MjA1In0.RxxsRCT9sroM5zW5e0nlevepnbQ48DArfp67ESOgNQ0'
								}
							}, function (err, response, body) {
								let src = JSON.parse(JSON.parse(body)).url;
								src = src.replace(/(http:|https:)*\/\/img.aliyin.com/g, 'http://img.aliyin.com')
								child.key = {
									src: src
								}
								child._html = `<g><image xlink:href='${src}!w800.src' width='${child.width}' height='${child.height}'></image></g>`;
								obj.children.push(child)
								resolve(child)
								fs.unlink(imagepath)
							})
							var formdata = r.form()
							formdata.append('TypeNum', 0)
							formdata.append('TypeCategoryNum', 0)
							formdata.append('KeyWords', 'sheji')
							formdata.append('file', fs.createReadStream(imagepath))
						})
					}
				} else {
					resolve()
				}
			})
		})).then(arr => {
			// console.log(arr, '所有的都结束')
			obj.children.reverse();
			fs.unlink(filePath);
			res.send(obj);
		})
	} catch (error) {
		console.log(error)
		res.send()
	}
})

router.post('/psd/upload', upload.single('files'), (req, res) => {
	let body = req.body;
	let files = req.file;
	// console.log(body, files)
	let filePath = files.path;
	var psd = PSD.fromFile(filePath);
	psd.parse();
	let doc = psd.tree().export();
	res.send(doc)
})


function getPath(obj) {
	let options = { // 文字属性设置
		fontSize: obj.size,
		anchor: 'top left',
		kerning: false,
		letterSpacing: obj.spacing,
	};
	// console.log(obj.size)
	// console.log(obj.family, '接受的字体')
	let family = path.resolve(`./font/${obj.family}.ttf`)
	let SVG = TextToSVG.loadSync(family); // 字体设置
	let result = countLine({
		obj,
		SVG,
		options
	})

	return result;
}
// getPath()
function countLine({
	obj,
	SVG,
	options
}) {
	let svg = '',
		w = 0,
		h = 0;
	obj.arrList.forEach((item, i) => {
		let path = SVG.getPath(item, options)
		let box = SVG.getMetrics(item, options)
		let g = `<g transform='translate(${-box.x},${ obj.line * obj.size * i })'>`
		g += path + '</g>'
		svg += g
		w = w < box.width ? box.width : w;
		h += box.height;
	})
	w += 10;
	return {
		svg,
		width: w,
		height: h
	}
};









module.exports = router;